package t2jumble;

import java.util.List;

import com.reeltwo.jumble.fast.JumbleResult;
import com.reeltwo.jumble.fast.MutationResult;
import com.reeltwo.jumble.ui.JumbleListener;

/**
 * Jumble listener which records the result of each mutation for later retrieval.
 */
public class JumbleRecorder implements JumbleListener {
	/**
	 * Cache for the results of each mutation, as reported by Jumble.
	 */
	private static MutationResult[] mResults;
	/**
	 * The current mutation number. <br />
	 * Range: 0 to mResults.length
	 */
	private static int mCurrentMutation;
	
	@Override
	public void jumbleRunStarted(String className, List<String> testNames) { 
		mResults = null;
		mCurrentMutation = 0;
	}
	
	@Override
	public void performedInitialTest(JumbleResult result, int mutationCount) { 
		mResults = new MutationResult[mutationCount];
		mCurrentMutation = 0;
	}
	
	@Override
	public void finishedMutation(MutationResult res) {
		mResults[mCurrentMutation++] = res;
	}
	
	@Override
	public void jumbleRunEnded() { 
		assert(resultsAreIn());
	}
	
	public void error(String errorMessage) { 
		System.err.println("Jumble Error: " + errorMessage);
	}
	
	/**
	 * Were the expected number of mutation results received from Jumble?
	 */
	private static boolean resultsAreIn() {
		return (mResults != null && mCurrentMutation == mResults.length);
	}
	
	public static MutationResult[] getResults() {
		if (!resultsAreIn()) {
			throw new IllegalStateException("Attempted to retrieve results before all mutations were completed.");
		}
		return mResults;
	}
}
